using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Survival;
using Survival.Services;


namespace Survival.Player
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class PlayerCharacter : Microsoft.Xna.Framework.DrawableGameComponent
    {
        IInputService inputService;
        Vector2 position;
        Vector2 Position { get { return position; } }

        const float playerMoveSpeed = 75f;

        SpriteBatch playerSpriteBatch;

        Texture2D playerSprite;

        public PlayerCharacter(Game game)
            : base(game)
        {
            position = new Vector2(400, 200);
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            inputService = (IInputService)Game.Services.GetService(typeof(IInputService));
            playerSpriteBatch = new SpriteBatch(GraphicsDevice);
        }

        protected override void LoadContent()
        {
            playerSprite = Game.Content.Load<Texture2D>("Player");
        }

        public override void Draw(GameTime gameTime)
        {
            playerSpriteBatch.Begin();
            playerSpriteBatch.Draw(playerSprite, position, Color.White);
            playerSpriteBatch.End();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            MovePlayer(gameTime);

            base.Update(gameTime);
        }

        private void MovePlayer(GameTime gameTime)
        {
            float elapsedTimeInSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
            int yOffset = 0, xOffset = 0;

            if (inputService.KeyPressed(Keys.W))
                yOffset -= 1;
            if (inputService.KeyPressed(Keys.S))
                yOffset += 1;
            if (inputService.KeyPressed(Keys.A))
                xOffset -= 1;
            if (inputService.KeyPressed(Keys.D))
                xOffset += 1;

            if (yOffset != 0 || xOffset != 0)
            {
                Vector2 moveDirection = Vector2.Normalize(new Vector2(xOffset, yOffset));
                position += moveDirection * (playerMoveSpeed * elapsedTimeInSeconds);
            }
        }
    }
}
